import { IHomeState, INewsList, IRetNewsData, NAV_TYPES } from '@/typings';
import * as actionTypes from './actionTypes';

export default {
  //更改isLoading的方法
  [actionTypes.SET_LOADING](state: IHomeState, isLoading: boolean) {
    state.newsList.isLoading = isLoading;
  },
  //数据请求成功后修改数据
  [actionTypes.SET_NEWS_LIST](state: IHomeState, payload: IRetNewsData) {
    //如果hasMore返回为真,证明还有下一页,那么就一定要合并state.news数据,并且要给pageNum+1,因为下一次请求的时候需要下一页的pageNum
    if (payload.hasMore) {
      //合并新的数组数据
      //payload.data! 有可能是null 加上 ! 确定它已经返回值了
      state.newsList.news = [...state.newsList.news, ...payload.data!];

      //还有数据
      state.newsList.pageNum += 1;
    }

    //不管hasMore返回的是真是假,都要重新赋值hasMore,都要关闭更多
    //更新hasMore
    state.newsList.hasMore = payload.hasMore;
    //关闭更多
    state.newsList.isLoading = false;
  },
  //修改新闻类型
  [actionTypes.SET_CURRENT_TYPE](state: IHomeState, type: NAV_TYPES) {
    state.currentType = type;

    //由于新闻类型改变,所以newsList所有属性都要还原成默认值
    state.newsList = <INewsList>{
      hasMore: true,
      isLoading: false,
      pageNum: 0,
      count: 10,
      news: []
    };
  }
};
